import { config } from '../../config/index';

/** 获取个人中心信息 */
function mockFetchUserCenter() {
  const { delay } = require('../_utils/delay');
  const { genUsercenter } = require('../../model/usercenter');
  return delay(1000).then(() => genUsercenter());
}

/** 获取个人中心信息 */
export function fetchUserCenter(updateUserinfoCallback, loginUrl='') {
  if(updateUserinfoCallback){
    updateUserinfoCallback({
      userInfo: {
        avatarUrl: '',
        nickName: '正在登录...',
        phoneNumber: '',
        address: ''
      },
      token: '',
      openid: '',
    })
  }

  // if (config.useMock) {
  //   return mockFetchUserCenter();
  // }

  return new Promise((resolve) => {
    wx.login({
      success: res => {
        console.log('wx.login success: ', res.code)
        resolve(res.code);
      }
    })
  }).then((code) => {
    if (code) {
      console.log('promise进then 1 code = : ', code)
      return new Promise((resolve, reject) => {
        console.log('login_url: ', loginUrl)
        wx.request({
          url: loginUrl,
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          data: {
            code: code
          },
          success: (res) => {
            console.log('wchatlogin返回 : ', res.data)
            if (res.data.status === 10000) {
              console.log(res.data.data);
              resolve(res.data.data);
            } else {
              reject(res);
            }
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    } else {
      return Promise.reject(new Error('未获取到有效的 code'));
    }
  }) .then(
    (responds) => {
      // 保存用户信息
      wx.setStorage({
        key: "key",
        data: responds,
        encrypt: true, // 若开启加密存储，setStorage 和 getStorage 需要同时声明 encrypt 的值为 true
        success() {
          wx.getStorage({
            key: "key",
            encrypt: true, // 若开启加密存储，setStorage 和 getStorage 需要同时声明 encrypt 的值为 true
            success(res) {
              console.log('设置成功，设置的数据为', res.data)
            }
          })
        }
      })
      
      return responds;
    },
  )
}
